package textviewer.main;

import java.util.ArrayList;

import android.widget.ScrollView;

public class BookMark {
	private FileIO fileio;
	private ScrollView scllview;
	private int x_pos;
	private int y_pos;
	private String topic;
	private String tmp_path;
	private String bookfolder;
	public BookMark(FileIO fileio, ScrollView scllview,String topic,String bookfolder)
	{
		this.fileio=fileio;
		this.scllview=scllview;
		this.topic=topic;
		this.bookfolder=bookfolder;
		x_pos=scllview.getScrollX();
		y_pos=scllview.getScrollY();
		tmp_path = fileio.get_sdcard_root()+bookfolder+"/index.dat";
	//	System.out.println(tmp_path );
	}
	public void SetTheBookMark()
	{
		x_pos=scllview.getScrollX();
		y_pos=scllview.getScrollY();
		if(!fileio.check_Fileexisted(tmp_path))
		{
			//System.out.println("Bookmark file is created.");
			ArrayList<String> tmp_array = new ArrayList<String>();
			tmp_array.add(topic+","+x_pos+","+y_pos);
			fileio.writefileOP(tmp_array , tmp_path, "UTF-8");
		}
		else
		{
			//System.out.println("Bookmark file is existed.");
			ArrayList<String> file_result = fileio.ReadfileOP(tmp_path, "UTF-8");
			boolean FindTheSpecificResult=false;
			int index_to_remove=0;
			for(int i=0;i<file_result.size();i++)
			{
				String[] split_str = file_result.get(i).split(",");
				if(split_str[0].equals(topic))
				{
					index_to_remove=i;
					FindTheSpecificResult=true;
				}
			}
			if(!FindTheSpecificResult)
			{
				file_result.add(topic+","+x_pos+","+y_pos);
			}
			else
			{
				file_result.remove(index_to_remove);
				file_result.add(topic+","+x_pos+","+y_pos);
			}
			FileIO.delete_file(tmp_path);
			fileio.writefileOP(file_result , tmp_path, "UTF-8");
		}
		return;
	}
	public boolean GetTheBookMark()
	{
		boolean FindTheSpecificResult=false;
		if(fileio.check_Fileexisted(tmp_path))
		{
			ArrayList<String> file_result = fileio.ReadfileOP(tmp_path, "UTF-8");
			
			for(int i=0;i<file_result.size();i++)
			{
				String[] split_str = file_result.get(i).split(",");
				if(split_str[0].equals(topic))
				{
					FindTheSpecificResult=true;
					for(int y=0;y<split_str.length;y++)
					{
						try
						{
						x_pos=Integer.parseInt(split_str[1]);
						y_pos=Integer.parseInt(split_str[2]);
						
						}
						catch(Exception e)
						{
							x_pos=0;
							y_pos=0;
						}
					}
				}
			}
		}
		else
		{
			//fileio.make_file(tmp_path);
		}
		return FindTheSpecificResult;
	}
	public void MoveTheScrollView()
	{
		System.out.println("x-pos:"+x_pos+"y-pos"+y_pos);
		//scllview.scrollBy(x_pos, y_pos);
		scllview.post(new Runnable() {
		public void run()
		{
			//int y = t.getLayout().getLineTop(40); // e.g. I want to scroll to line 40 
			scllview.scrollTo(x_pos, y_pos);
		}
		});
	}
	
}
